package com.chencl.cipher.util;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.tomcat.util.codec.binary.Base64;

/**
 * @ClassName:  AESUtils   
 * @Description: 对称加密
 * @author: Ccl
 * @date:   2021年11月25日 下午4:55:45      
 * @Copyright:
 */
public class AESUtils {
	
	/**
	 * 
	 * @Title: encrypt   
	 * @Description: 解密
	 * @param: @param content
	 * @param: @param secretKey
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String encrypt(String content,String secretKey){
		try {
			SecretKeySpec secretKeySpec = getSecretKeySpec(secretKey);
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
			byte[] bytes = cipher.doFinal(content.getBytes());
			return new String(Base64.encodeBase64(bytes), "UTF-8"); 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
	
	/**
	 * 
	 * @Title: decrypt   
	 * @Description: 加密
	 * @param: @param content
	 * @param: @param secretKey
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String decrypt(String content,String secretKey){
		try {
			SecretKeySpec secretKeySpec = getSecretKeySpec(secretKey);
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
			byte[] bytes = cipher.doFinal(Base64.decodeBase64(content.getBytes("UTF-8")));
			return new String(bytes,"UTF-8");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return null;
	}
	
	public static SecretKeySpec getSecretKeySpec(String secretKey){
		try {
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			keyGenerator.init(128,new SecureRandom(secretKey.getBytes()));
			SecretKey secretKey2 = keyGenerator.generateKey();
			SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey2.getEncoded(),"AES");
			return secretKeySpec;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		String content = "dfdfdfd";
		String secretKey = "112211";
		String encode = encrypt(content, secretKey);
		String decode = decrypt(encode, secretKey);
		System.out.println(encode);
		System.out.println(decode);
	}

}
